import {
	checkLogin
} from './auth.js'
new Vue({
	el: '#app',
	data: {
		IS_LOGIN: null,
		searchKey: '', // 搜索的关键词
		cartList: [],
		totalPrice: 999,
		totalNum: 0
	},
	watch: {
		cartList: {
			deep: true,
			immediate: true,
			handler(val) {
				this.totalPrice = 0
				this.totalNum = 0
				for (let i = 0; i < this.cartList.length; i++) {
					const element = this.cartList[i];
					if (this.cartList[i].checked) {
						this.totalPrice += element.price * element.num
						this.totalNum += element.num
					}
				}
			}
		}
	},
	computed: {
		checkAll: {
			get() {
				return this.cartList.every(item => item.checked)
			},
			set(val) {
				for (let i = 0; i < this.cartList.length; i++) {
					this.cartList[i].checked = val
				}
			}
		}
	},
	async created() {
		this.IS_LOGIN = await checkLogin()
		if (this.IS_LOGIN == null) {
			location.href = '/'
		}
	},
	async mounted() {
		await this.getCartList()
	},
	methods: {
		// 结算
		account() {
			let params = ''
			for (let i = 0; i < this.cartList.length; i++) {
				const element = this.cartList[i];
				if (element.checked) {
					params += element.cid + ','
				}
			}
			params = params.substring(0, params.length - 1)
			if (params == '') {
				this.$message.error('请选择商品')
				return
			}
			location.href = `/web/orderConfirm.html?itemIds=${params}`
		},
		// 删除商品
		async deleteItem(itemId) {
			const res = await request.delete('/cart/deleteItem', {
				params: {
					itemId
				}
			})
			if (res.code === 200) {
				this.$message.success('删除成功')
				this.getCartList()
			}
		},
		// 修改商品数量
		async changeNum(changedNum, itemId) {
			await request.post('/cart/changeNum', {
				itemId,
				num: changedNum
			})
			this.getCartList()
		},
		async getCartList() {
			const res = await request.get('/cart/getCartList')
			this.cartList = res.data
			// 后加的属性不是响应式的，因此要在初始化的时候就把属性加入进去
			this.cartList = res.data.map(item => {
				return {
					...item,
					checked: item.checked !== undefined ? item.checked : false
				}
			})
		},
		// 查找商品
		searchProduct() {
			console.log('查找商品:');
			location.href = `../web/search.html?searchKey=${this.searchKey}`
		},
		// 退出登录
		logout() {
			localStorage.removeItem('token')
			this.IS_LOGIN = null
			this.$message.success('退出成功')
			location.href = '/'
		},
	}
})